import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'


import { Form, Select, message, Button, Spin } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import debounce from 'lodash.debounce'
import menuRoute from 'routes/menuRoute'
import moment from 'moment'

import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/new-agency.scss'


class NewAgency extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      principalValidateStatus: '',  //被代理人校验
      principalHelp: '', //被代理人校验内容
      fetching: false,
      agencySetting:  menuRoute.getRouteItem('agency-setting','key'),    //代理设置
      agencyDetail:  menuRoute.getRouteItem('agency-detail','key'),    //代理详情
      selectValue:false //Select input里是否存在值
    };
    this.searchValue = debounce(this.searchValue, 250);
  }

  handleChange = (value) => {
    if (!value) {
      this.setState({
        principalValidateStatus: 'error',
        principalHelp: messages('setting.key43'/*请选择*/),//"请选择",
      })
    } else {
      this.setState({ selectValue: true })
    }
  };

  //查询被代理人下拉列表
  handleSearch = (value) => {
    let principalInfo = this.props.form.getFieldValue('principalInfo');
    if (!value && principalInfo && !this.state.data.length) {
      try {
        if (typeof JSON.parse(principalInfo) === 'object') {
          this.setState({ data: [JSON.parse(principalInfo)], fetching: false })
        }
      } catch(e) {
        this.setState({ fetching: false })
      }
    }
    this.searchValue(value);
  };

  searchValue = (value) => {
    const { tab } = this.props.location.query;
    value && this.setState({
      principalValidateStatus: '',
      principalHelp: '',
      fetching: true
    });
    let params = {
      page: 0,
      size: 1000,
      keyword: value,
      status: 'all',
    };
    // params.status = tab === 'apply' ? undefined : 'all'; //undefined为不传status参数，查出的为在职和待离职人员
    value && value.length && agencyService.getPersonByValueV2(params).then(res => {
      let resultData = [];
      let data = res.data;
      data.map(item => {
        item.text = `${item.fullName} ${item.firstName} ${item.lastName} - ${item.eid}`;
        //只支持工号和姓名搜索，手机和邮箱要去除
        if (item.text.indexOf(value.toLowerCase()) > -1 || item.text.indexOf(value.toUpperCase()) > -1) {
          resultData.push(item);
        }
      });
      this.setState({ data: resultData, fetching: false });
    });
  };

  //选中被代理人后查询该被代理人状态（是否已存在、是否将离职）
  handleSelect = (values) => {
    let principalInfo = JSON.parse(values);
    principalInfo.userOID && agencyService.getPersonStatusByOid(principalInfo.userOID, this.props.location.query.tabKey).then(res => {
      if (res.data) {
        this.setState({
          principalValidateStatus: 'error',
          principalHelp: messages('setting.key1'/*此员工已存在被代理信息，请返回至前一页面搜索该员工并编辑*/)        })
      } else {
        let leaveTime = moment(principalInfo.leavingDate).format('YYYY-MM-DD');
        if (principalInfo.status === 1002) {
          this.setState({
            principalValidateStatus: 'warning',
            principalHelp: messages('setting.key1433',{arg1: leaveTime}/*该员工将于 {arg1} 离职*/) +
                           `${this.props.location.query.tab === 'apply' ? messages('setting.key2'/*，离职后此代理将自动禁用*/) : ''}`
          })
        } else if (principalInfo.status === 1003) {
          this.setState({
            principalValidateStatus: 'warning',
            principalHelp: messages('setting.key1434',{arg1: leaveTime}/*该员工已于 {arg1} 离职*/) //该员工已于 {time} 离职
          })
        } else {
          this.setState({
            selectValue: false,
            principalValidateStatus: '',
            principalHelp: ''
          })
        }
      }
    });
  };

  //保存被代理人
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        this.setState({
          principalValidateStatus: 'error',
          principalHelp: messages('setting.key43'/*请选择*/),
        })
      } else {
        if (this.state.principalValidateStatus === 'error') return;
        let principalInfo = JSON.parse(values.principalInfo);
        principalInfo.billProxyRuleDTOs = [];
        principalInfo.enabled = false;
        principalInfo.principalOID = principalInfo.userOID;
        principalInfo.proxyOperationType = this.props.location.query.tabKey; //proxyOperationType：1（代理制单）、2（代理审批）

        this.setState({loading: true});
        agencyService.newAgency(principalInfo).then(res => {
          this.setState({ loading: false });
          message.success(messages('common.create.success', {name: ''}));
          this.context.router.push(this.state.agencyDetail.url.replace(':principalOID', res.data.principalOID) + `?tab=${this.props.location.query.tab}&tabKey=${this.props.location.query.tabKey}`);
        }).catch(e => {
          this.setState({loading: false});
          message.error(`${messages('common.create.filed')}， ${e.response.data.message}`)
        })
      }
    });
  };

  //取消新建代理
  handleCancel = () => {
    this.context.router.replace(this.state.agencySetting.url + `?tab=${this.props.location.query.tab}`);
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { loading, data, principalValidateStatus, principalHelp, fetching, selectValue } = this.state;
    return (
      <div className="new-agency">
        <h3 className="header-title">{messages('setting.key44'/*请选择被代理人*/)}</h3>
        <Form onSubmit={this.handleSave}>
          <FormItem colon={false}
                    validateStatus={principalValidateStatus}
                    help={principalHelp}
                    className="principal-item"
                    label={
                      <span>
                        {messages('setting.key3'/*被代理人*/)} :
                        <span className="principal-explain">
                          {this.props.location.query.tab === 'apply' ?
                            messages('setting.key4'/*需要他人帮助其填写、提交相应单据的人*/) :
                            this.props.location.query.tab === 'approve' ?
                            messages('setting.key5'/*需要他人帮助其审批相应单据的人*/):
                            messages('setting.key2835'/*需要他人帮助操作账本及消费记录*/)}  
                        </span>
                      </span>
                    }>
            {getFieldDecorator('principalInfo', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }]})(
              <Select placeholder={messages('setting.key6'/*请输入姓名/工号*/)}
                      allowClear
                      showSearch
                      filterOption={false}
                      //combobox模式下会导致第一次输入时会导致页面会自动右移并释放输入框的焦点 bug 17503
                      // mode={(data.length || selectValue) ? null : 'combobox'}
                      notFoundContent={fetching ? <Spin size="small" /> : messages('setting.key7'/*无匹配结果*/)}
                      onChange={this.handleChange}
                      onSearch={this.handleSearch}
                      onSelect={this.handleSelect}
                      getPopupContainer={triggerNode => triggerNode.parentNode}>
                {data.map(d => <Option key={JSON.stringify(d)}>{d.text}</Option>)}
              </Select>
            )}
          </FormItem>
          <div>
            <Button type="primary" htmlType="submit" loading={loading} className="save-btn">{messages('common.save')}</Button>
            <Button onClick={this.handleCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

NewAgency.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

const WrappedNewAgency = Form.create()(NewAgency);

export default connect(mapStateToProps)(WrappedNewAgency);
